﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MapLibrary.GUI;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GUILibrary
{
    public class HorizontalBar : Component
    {

        public string BaseImageName
        {
            get;
            set;
        }

        public string FillImageName
        {
            get;
            set;
        }

        public Vector2 ProgressOffset
        {
            get;
            set;
        }

        public int EffectiveWidth
        {
            get;
            set;
        }

        [ContentSerializerIgnore]
        public int ValueToTrack
        {
            get { return ToTrack.GetAmount(Name);  }
        }

        [ContentSerializerIgnore]
        public ITrackable ToTrack
        {
            get { return toTrack; }
            set
            {
                toTrack = value;
                CheckAndTriggerInitialize();
            }
        }

        [ContentSerializerIgnore]
        public int MaximumValue
        {
            get { return toTrack.GetMax(Name); }
        }

        private Texture2D baseImage;
        private Texture2D fillImage;
        private ITrackable toTrack;

        private int fillImageWidth;

        public override void Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch batch)
        {
            batch.Draw(baseImage, ScreenPosition, Color.White);

            float percent = CalculatePercent();
            int numBars = (int)((EffectiveWidth * percent) / fillImageWidth);
            Vector2 startPos = ScreenPosition + ProgressOffset;
            for (int i = 0; i < numBars; i++)
            {
                batch.Draw(fillImage, startPos + (i * new Vector2(fillImageWidth,0)), Color.White);
            }
        }

        public override void Load(Microsoft.Xna.Framework.Content.ContentManager cm)
        {
            //initialize some values
            Action = "HorizontalBar";

            baseImage = cm.Load<Texture2D>(BaseImageName);
            fillImage = cm.Load<Texture2D>(FillImageName);
            fillImageWidth = fillImage.Bounds.Width;
        }

        private float CalculatePercent()
        {
            if (!Initialized)
                return 0.0f;
            else
            {
                return (float)ValueToTrack / MaximumValue;
            }
        }

        private void CheckAndTriggerInitialize()
        {
            Initialized = toTrack != null;
        }
    }
}
